<template>
	<view class="sentence-box">
		<template v-for="(item, _index) in viewSentence" :key="_index">
			<text v-if="item.Index !== null" class="word" :style="item.style">{{item.text}}</text>
			<text v-else style="margin-right: 0.3ch;">{{item.text}}</text>	
		</template>
		<u-icon v-if="play" style="vertical-align:middle;margin-top: -5px;text-indent: 0;" name="volume" color="#332c2b" size="40"></u-icon>
	</view>
</template>

<script lang="ts" setup>
	import { ref, computed } from 'vue';
	import { ISentence, IWord } from '@/store/study';

	/** 英文句子显示 */
	defineOptions({ name: 'sentence-linght-words', inheritAttrs: false });
	
	type IProps = { words?: IWord[] | IWord; sentence: ISentence; play?: boolean }
	const props = withDefaults(defineProps<IProps>(), { words: () => [], play: false });
	
	const sentenceWords = ref<any[]>([]);
	
	
	const punctuationMark = ['.', ',', '?', '!'];
	const viewSentence = computed(() => {
		let tempSentenceEn: string = props.sentence.SentenceEn || '';
		const words = Array.isArray(props.words) ? props.words : [props.words];
		if (tempSentenceEn) {
			// 建立索引关系
			const sententceWordSp = tempSentenceEn.split(' ');
			return sententceWordSp.flatMap((sp, index) => {
				const indexWords = props.sentence.WordIds.filter(item => item.Index.includes(index + 1))
				const isActive = words.some(item => indexWords.some(iw => iw.ID === item.WordId))
				if (punctuationMark.some(mark => sp.endsWith(mark))) {
					const word = sp.substring(0, sp.length - 1);
					const mark = sp.substring(sp.length - 1);
					return [
						// { Index: index + 1, text: word, style: isActive ? 'color:rgb(60, 166, 146);font-weight: 600;font-size:20px;': '' },
						{ Index: index + 1, text: word, style: isActive ? 'font-weight: 600;text-decoration: underline;': '' },
						{ Index: null, text: mark },
						{ Index: null, text: ' ' }
					]
				}
				
				return [
					// { Index: index + 1, text: sp, style: isActive ? 'color:rgb(60, 166, 146);font-weight: 600;font-size:20px;': '' },
					{ Index: index + 1, text: sp, style: isActive ? 'font-weight: 600;text-decoration: underline;': '' },
					{ Index: null, text: ' ' }
				]
			})
		}
		return [];
	})
	// console.log('words', props.words)
</script>

<style scoped>
	.sentence-box{
		text-indent: 2em;
	}
	.sentence-box text{
		text-indent: 0;
	}
</style>